<?php

namespace App\Models;

use App\Handlers\KeysHandler;
use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Cache;


class User extends Model
{
	use HasDateTimeFormatter;
    use HasFactory;
    //0禁用  1未提交  2审核中  3审核不通  4审核通过
    const STATE_DISABLE = 0;
    const STATE_UNSUBA = 1;
    const STATE_REVIEW = 2;
    const STATE_FAIL = 3;
    const STATE_PASS = 4;
    const STATES = [
        self::STATE_DISABLE => '禁用',
        self::STATE_UNSUBA => '未提交',
        self::STATE_REVIEW => '审核中',
        self::STATE_FAIL => '审核拒绝',
        self::STATE_PASS => '审核通过',
    ];

    const SHOPTAYES = [
        0 => '未知',
        1 => '个人',
        2 => '独资',
        3 => '公司',
        4 => '集团'
    ];


    protected $fillable = [
        'agent_id', 'parent_id', 'tiktokid', 'tiktokno', 'nickname', 'avatar', 'state', 'balance', 'freeze_balance', 'lang', 'timezone', 'remark', 'payment_password', 'shoptype', 'shopname', 'shopdesc', 'identity', 'shopstar', 'shopcredit','parent_id', 'relation', 'login_time_last','review_time'
    ];

    //商品橱窗
    public function agent()
    {
        return $this->hasOne(Administrator::class,'id','agent_id');
    }

    public function hierarchy()
    {
        return $this->belongsTo(Hierarchy::class);
    }

    //商品橱窗
    public function shopwindows(): HasMany
    {
        return $this->hasMany(Shopwindow::class);
    }

    //商品橱窗
    public function shopwindowsshelves(): HasMany
    {
        return $this->hasMany(Shopwindow::class)->where('shelves','=',1);
    }

    //投诉反馈
    public function complaints(): HasMany
    {
        return $this->hasMany(Complaint::class);
    }

    //充值提现
    public function order(): HasMany
    {
        return $this->hasMany(Order::class);
    }


    //后台下拉获取会员
    public static function getUsers(){
        $users = self::query()->pluck('tiktokno','id')->toArray();
        foreach ($users as $key=>&$user){
            $user = $key."({$user})";
        }
        return $users;
    }


    /**
     * 获取用户
     * @where   条件
     * @cache   是否缓存中读取
     * **/
    public static function getUser($where = [],$cache = 1){
        if ($cache && ( isset($where['id']) || isset($where['tiktokid']) ) )
        {
            if (isset($where['id'])){
                $key = sprintf(KeysHandler::USER_INFO, 'id', $where['id']);
            }elseif (isset($where['tiktokid'])){
                $key = sprintf(KeysHandler::USER_INFO, 'tiktokid', $where['tiktokid']);
            }
            $user = Cache::get($key);

            if(!empty($user)){
                //每5分钟更新一次,登录时间
                if(Carbon::now()->timestamp -  Carbon::parse($user->login_time_last)->timestamp > 5*60){
                    $ip = request()->ip();
                    $user->ip_last = $ip;
                    $user->login_time_last = now();
                    $user->save();
                }
                return $user;
            }
        }

        $lock = Cache::lock(KeysHandler::USER_INFO_DATA_LOCK, 2);
        if(!$lock->get()) {
            usleep(100000); //睡眠100ms
            return self::getUser($where,$cache);
        }
        $user = self::where($where)->first();
        if ($user){
            $key_id = sprintf(KeysHandler::USER_INFO, 'id', $user->id);
            $key_tiktokid = sprintf(KeysHandler::USER_INFO, 'tiktokid', $user->tiktokid);
            Cache::put($key_id, $user, 3600);
            Cache::put($key_tiktokid, $user, 3600);
        }
        $lock->release();
        return $user;
    }


    public static function getShop($tiktokno){
        //后期可优化为有序集合中差会员ID,再使用getUser方法获取数据
        $user = self::where('tiktokno','=',$tiktokno)->first();
        return $user;
    }







}
